<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import {
    UserBindDept,
    UserBindRole,
    UserById,
    UserDeleteById,
    UserPage,
    UserSave,
    UserUpdate,
  } from '@/api/UserApi';
  import { RoleList } from '@/api/RoleApi';
  import { DeptTree } from '@/api/DeptApi';

  const treeData = ref();
  const loadTree = async () => {
    const { code, data } = await DeptTree();
    treeData.value = data;
    console.log(data);
  };
  const createForm = ref();
  const updateForm = ref();
  const updateRequest = ref({
    name: null,

    loginName: null,

    email: null,

    sex: null,

    phone: null,

    password: null,

    slat: null,

    id: null,
  });
  const visibleShow = ref(false);
  const handleCancelShow = () => {
    visibleShow.value = false;
  };
  const handleOkShow = () => {
    visibleShow.value = false;
  };
  const visibleUpdate = ref(false);
  const handleCancelUpdate = () => {
    visibleShow.value = false;
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      slotName: 'name',
    },

    {
      title: '登录名',
      dataIndex: 'loginName',
      slotName: 'loginName',
    },

    {
      title: '邮箱',
      dataIndex: 'email',
      slotName: 'email',
    },

    {
      title: '性别',
      dataIndex: 'sex',
      slotName: 'sex',
    },

    {
      title: '手机号',
      dataIndex: 'phone',
      slotName: 'phone',
    },

    {
      title: '操作列',
      dataIndex: 'operations',
      slotName: 'operations',
    },
  ];
  const response = ref([]);
  const visible = ref(false);
  const pagination = reactive({
    current: 0,
    pageSize: 10,
  });
  const bindDeptParam = ref({
    mainDeptId: null,
    deptIds: null,
  });
  const queryRequest = ref({
    name: null,

    loginName: null,

    email: null,

    sex: null,

    phone: null,

    password: null,

    slat: null,
  });
  const search = async () => {
    console.log('search');

    const { data } = await UserPage(queryRequest.value, {
      pageSize: 10,
      current: 0,
    });
    response.value = data.records;
    pagination.total = data.total;
    pagination.current = data.current;
    console.log(data);
  };

  const onPageChange = async (current: number) => {
    pagination.current = current;
    const param = {
      pageSize: pagination.pageSize,
      current,
    };
    const { data } = await UserPage(queryRequest.value, param);
    response.value = data.records;
  };

  const fetchData = async () => {
    const { data } = await UserPage(queryRequest.value, pagination);
    response.value = data.records;
    pagination.total = data.total;
    pagination.current = data.current;
    console.log(data);
  };
  const reset = async () => {
    console.log('reset');
    queryRequest.value = {};
    const { data } = await UserPage(queryRequest.value, {
      current: 0,
      pageSize: 10,
    });
    response.value = data.records;
    pagination.total = data.total;
  };
  const createRequest = ref({
    name: null,

    loginName: null,

    email: null,

    sex: null,

    phone: null,

    password: null,

    slat: null,
  });

  const handleOkCreate = async () => {
    const err = await createForm.value.validate();
    if (err) {
      return false;
    }
    await UserSave(createRequest.value).then((res) => {
      if (res.code === 20000) {
        Message.success('创建成功');
        createRequest.value = {};
        visible.value = false;
        reset();
      } else {
        Message.error('创建失败');
        createRequest.value = {};
      }
    });
    return true;
  };
  const handleCancelCreate = () => {
    createRequest.value = {};
    visible.value = false;
  };

  const show = async (record: any) => {
    const { data } = await UserById(record.id);
    updateRequest.value = data;
    visibleShow.value = true;
    console.log('show');
  };
  const roleDiag = ref(false);

  const roleListRef = ref();
  const bindRoleId = ref();
  const curUserId = ref();
  const bindRoleIdVal = ref();
  const settingRole = async (record: any) => {
    const roc = await UserById(record.id);

    curUserId.value = record.id;
    const { data } = await RoleList();
    const arr = [];
    // eslint-disable-next-line no-restricted-syntax
    for (const i of data) {
      arr.push({
        value: i.id,
        label: i.name,
      });
    }
    roleListRef.value = arr;
    const roleIds = [];
    const roleName = [];
    // eslint-disable-next-line no-restricted-syntax,no-unsafe-optional-chaining
    for (const i of roc.data?.roles) {
      roleIds.push(i.id);
      roleName.push(i.name);
    }

    bindRoleId.value = roleName;
    bindRoleIdVal.value = roleIds;
    roleDiag.value = true;
  };

  const deptDiag = ref(false);
  const deptBindAction = async () => {
    console.log(bindDeptParam.value);
    let arr = [];
    if (bindDeptParam.value.deptIds) {
      arr = arr.concat(bindDeptParam.value.deptIds);
    }
    if (bindDeptParam.value.mainDeptId) {
      arr.push(bindDeptParam.value.mainDeptId);
    }
    const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index);

    debugger;
    await UserBindDept({
      userId: curUserId.value,
      deptIds: uniqueArr,
      mainDeptId: bindDeptParam.value.mainDeptId,
    }).then((res) => {
      if (res.code === 20000) {
        Message.success('设置成功');
      } else {
        Message.success('设置失败');
      }
    });
    // deptDiag.value = false;
  };
  const settingDept = async (record: any) => {
    curUserId.value = record.id;
    const { data } = await UserById(record.id);

    bindDeptParam.value.mainDeptId =
      data.mainDeptId === 0 ? null : data.mainDeptId;
    bindDeptParam.value.deptIds = data.deptIds;
    deptDiag.value = true;
  };
  const update = async (record: any) => {
    const { data } = await UserById(record.id);
    visibleUpdate.value = true;
    updateRequest.value = data;
    console.log('update');
  };
  const delte = async (record: any) => {
    console.log('delete');
    const { code } = await UserDeleteById(record.id);
    if (code === 20000) {
      Message.success('删除成功');
      reset();
    } else {
      Message.success('删除失败');
    }
  };
  onMounted(async () => {
    await loadTree();
    await fetchData();
  });
  const handleOkUpdate = async () => {
    debugger;
    const err = await updateForm.value.validate();
    if (err) {
      return false;
    }
    debugger;
    const { code } = await UserUpdate(updateRequest.value);
    if (code === 20000) {
      Message.success('修改成功');
      visibleShow.value = false;
      reset();
    } else {
      Message.error('修改失败');
    }
    return true;
  };
  const userBindRole = async () => {
    const { code, data } = await UserBindRole({
      userId: curUserId.value,
      roleIds: bindRoleIdVal.value,
    });
    if (code === 20000) {
      Message.success('绑定成功');
      roleDiag.value = false;
    } else {
      Message.success('绑定失败');
    }
  };
</script>

<template>
  <div>
    <div class="container">
      <a-card class="general-card" title="用户管理">
        <a-row>
          <a-col :flex="1">
            <a-form
              :label-col-props="{ span: 6 }"
              :model="queryRequest"
              :wrapper-col-props="{ span: 18 }"
              label-align="left"
            >
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-form-item field="name" label="姓名">
                    <a-input
                      v-model="queryRequest.name"
                      placeholder="请输入姓名"
                    >
                    </a-input>
                  </a-form-item>
                </a-col>

                <a-col :span="8">
                  <a-form-item field="loginName" label="登录名">
                    <a-input
                      v-model="queryRequest.loginName"
                      placeholder="请输入登录名"
                    >
                    </a-input>
                  </a-form-item>
                </a-col>

                <a-col :span="8">
                  <a-form-item field="email" label="邮箱">
                    <a-input
                      v-model="queryRequest.email"
                      placeholder="请输入邮箱"
                    >
                    </a-input>
                  </a-form-item>
                </a-col>

                <a-col :span="8">
                  <a-form-item field="sex" label="性别">
                    <a-select
                      v-model="queryRequest.sex"
                      :style="{ width: '320px' }"
                      placeholder="请选择性别"
                    >
                      <a-option>男</a-option>
                      <a-option>女</a-option>
                      <a-option>保密</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :span="8">
                  <a-form-item field="phone" label="手机号">
                    <a-input
                      v-model="queryRequest.phone"
                      placeholder="请输入手机号"
                    >
                    </a-input>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
          <a-divider direction="vertical" style="height: 84px" />
          <a-col :flex="'86px'" style="text-align: right">
            <a-space :size="18" direction="vertical">
              <a-button type="primary" @click="search">
                <template #icon>
                  <icon-search />
                </template>
                查询
              </a-button>
              <a-button @click="reset">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>

        <a-card>
          <a-button type="primary" @click="visible = true">
            <template #icon>
              <icon-plus />
            </template>
            新增
          </a-button>
          <a-table
            :columns="columns"
            :data="response"
            :pagination="pagination"
            @page-change="onPageChange"
          >
            <template #operations="{ record }">
              <a-button size="small" type="text" @click="show(record)">
                查看
              </a-button>
              <a-button size="small" type="text" @click="settingRole(record)">
                设置角色
              </a-button>
              <a-button size="small" type="text" @click="settingDept(record)">
                设置部门
              </a-button>
              <a-button size="small" type="text" @click="update(record)">
                修改
              </a-button>

              <a-button size="small" type="text" @click="delte(record)"
                >删除
              </a-button>
            </template>
          </a-table>
        </a-card>
      </a-card>
    </div>
    <!--    设置部门-->
    <a-modal
      v-model:visible="deptDiag"
      width="40%"
      @cancel="
        () => {
          deptDiag = false;
        }
      "
      @ok="deptBindAction"
    >
      <a-form ref="createForm" :model="createRequest" layout="vertical">
        <a-space :size="16" direction="vertical">
          <a-card class="general-card">
            <a-row :gutter="80">
              <a-col :span="16">
                <a-form-item field="pid" label="主部门">
                  <a-tree-select
                    v-model="bindDeptParam.mainDeptId"
                    :data="treeData"
                    :field-names="{
                      key: 'id',
                      title: 'name',
                      children: 'children',
                    }"
                    placeholder="请选择主部门"
                  >
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item field="pid" label="所属部门">
                  <a-tree-select
                    v-model="bindDeptParam.deptIds"
                    :data="treeData"
                    :field-names="{
                      key: 'id',
                      title: 'name',
                      children: 'children',
                    }"
                    multiple
                    placeholder="请选择所属部门"
                  >
                  </a-tree-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-space>
      </a-form>
    </a-modal>
    <!--设置角色-->
    <a-modal
      v-model:visible="roleDiag"
      width="25%"
      @cancel="
        () => {
          roleDiag = false;
        }
      "
      @ok="userBindRole"
    >
      <template #title> 配置角色</template>

      <a-transfer
        v-model="bindRoleIdVal"
        :data="roleListRef"
        :title="['未选择', '已选择']"
      >
      </a-transfer>
    </a-modal>
    <!--    新增-->
    <a-modal
      v-model:visible="visible"
      width="70%"
      :on-before-ok="handleOkCreate"
      @cancel="handleCancelCreate"
    >
      <template #title> 创建</template>
      <a-form ref="createForm" :model="createRequest" layout="vertical">
        <a-space :size="16" direction="vertical">
          <a-card class="general-card">
            <a-row :gutter="80">
              <a-col :span="8">
                <a-form-item
                  :rules="[
                    {
                      type: 'string',
                      required: true,
                      message: '姓名必填',
                    },
                  ]"
                  :validate-trigger="['change', 'blur']"
                  field="name"
                  label="姓名"
                >
                  <a-input
                    v-model="createRequest.name"
                    placeholder="请输入姓名"
                  >
                  </a-input>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item
                  :rules="[
                    {
                      type: 'string',
                      required: true,
                      message: '登录名必填',
                    },
                  ]"
                  :validate-trigger="['change', 'blur']"
                  field="loginName"
                  label="登录名"
                >
                  <a-input
                    v-model="createRequest.loginName"
                    placeholder="请输入登录名"
                  >
                  </a-input>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item
                  :rules="[
                    {
                      type: 'string',
                      required: true,
                      message: '邮箱必填',
                    },
                  ]"
                  :validate-trigger="['change', 'blur']"
                  field="email"
                  label="邮箱"
                >
                  <a-input
                    v-model="createRequest.email"
                    placeholder="请输入邮箱"
                  >
                  </a-input>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item
                  :rules="[
                    {
                      type: 'string',
                      required: true,
                      message: '性别必填',
                    },
                  ]"
                  :validate-trigger="['change', 'blur']"
                  field="sex"
                  label="性别"
                >
                  <a-select
                    v-model="createRequest.sex"
                    :style="{ width: '320px' }"
                    placeholder="请选择性别"
                  >
                    <a-option>男</a-option>
                    <a-option>女</a-option>
                    <a-option>保密</a-option>
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item
                  :rules="[
                    {
                      type: 'string',
                      required: true,
                      message: '手机号必填',
                    },
                  ]"
                  :validate-trigger="['change', 'blur']"
                  field="phone"
                  label="手机号"
                >
                  <a-input
                    v-model="createRequest.phone"
                    placeholder="请输入手机号"
                  >
                  </a-input>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item
                  :rules="[
                    {
                      type: 'string',
                      required: true,
                      message: '密码必填',
                    },
                  ]"
                  :validate-trigger="['change', 'blur']"
                  field="password"
                  label="密码"
                >
                  <a-input
                    v-model="createRequest.password"
                    placeholder="请输入密码"
                  >
                  </a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-space>
      </a-form>
    </a-modal>

    <!--    修改-->
    <a-modal
      v-model:visible="visibleUpdate"
      width="70%"
      :on-before-ok="handleOkUpdate"
      @cancel="handleCancelUpdate"
    >
      <template #title> 修改</template>
      <a-form ref="updateForm" :model="updateRequest" layout="vertical">
        <a-space :size="16" direction="vertical">
          <a-card class="general-card">
            <a-row :gutter="80">
              <a-col :span="8">
                <a-form-item
                  :rules="[
                    {
                      type: 'string',
                      required: true,
                      message: '姓名必填',
                    },
                  ]"
                  :validate-trigger="['change', 'blur']"
                  field="name"
                  label="姓名"
                >
                  <a-input
                    v-model="updateRequest.name"
                    placeholder="请输入姓名"
                  >
                  </a-input>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item
                  :rules="[
                    {
                      type: 'string',
                      required: true,
                      message: '登录名必填',
                    },
                  ]"
                  :validate-trigger="['change', 'blur']"
                  field="loginName"
                  label="登录名"
                >
                  <a-input
                    v-model="updateRequest.loginName"
                    placeholder="请输入登录名"
                  >
                  </a-input>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item
                  :rules="[
                    {
                      type: 'string',
                      required: true,
                      message: '邮箱必填',
                    },
                  ]"
                  :validate-trigger="['change', 'blur']"
                  field="email"
                  label="邮箱"
                >
                  <a-input
                    v-model="updateRequest.email"
                    placeholder="请输入邮箱"
                  >
                  </a-input>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item
                  :rules="[
                    {
                      type: 'string',
                      required: true,
                      message: '性别必填',
                    },
                  ]"
                  :validate-trigger="['change', 'blur']"
                  field="sex"
                  label="性别"
                >
                  <a-select
                    v-model="updateRequest.sex"
                    :style="{ width: '320px' }"
                    placeholder="请选择性别"
                  >
                    <a-option>男</a-option>
                    <a-option>女</a-option>
                    <a-option>保密</a-option>
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item
                  :rules="[
                    {
                      type: 'string',
                      required: true,
                      message: '手机号必填',
                    },
                  ]"
                  :validate-trigger="['change', 'blur']"
                  field="phone"
                  label="手机号"
                >
                  <a-input
                    v-model="updateRequest.phone"
                    placeholder="请输入手机号"
                  >
                  </a-input>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item field="password" label="密码">
                  <a-input
                    v-model="updateRequest.password"
                    placeholder="请输入密码"
                  >
                  </a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-space>
      </a-form>
    </a-modal>

    <!--    查看-->
    <a-modal
      v-model:visible="visibleShow"
      width="70%"
      @cancel="handleCancelShow"
      @ok="handleOkShow"
    >
      <template #title> 详情</template>
      <a-form :model="updateRequest" layout="vertical">
        <a-space :size="16" direction="vertical">
          <a-card class="general-card">
            <a-row :gutter="80">
              <a-col :span="8">
                <a-form-item field="name" label="姓名">
                  <a-input v-model="updateRequest.name" disabled></a-input>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item field="loginName" label="登录名">
                  <a-input v-model="updateRequest.loginName" disabled></a-input>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item field="email" label="邮箱">
                  <a-input v-model="updateRequest.email" disabled></a-input>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item field="sex" label="性别">
                  <a-input v-model="updateRequest.sex" disabled></a-input>
                </a-form-item>
              </a-col>

              <a-col :span="8">
                <a-form-item field="phone" label="手机号">
                  <a-input v-model="updateRequest.phone" disabled></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-space>
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
  .container {
    padding: 0 20px 20px 20px;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }

  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }

  .setting {
    display: flex;
    align-items: center;
    width: 200px;

    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
